package com.ajk.server.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity.BodyBuilder;
import org.springframework.stereotype.Service;

import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.Pay;
import com.ajk.server.service.PayService;
import com.ajk.server.utils.AjkUtil;
import com.ajk.shop.model.OrderInfo;
import com.ajk.shop.service.OrderService;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.model.Charge;

@Service
public class PayServiceImpl implements PayService{

	@Autowired
	private OrderService orderService;
	
	private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
	
	@Override
	public Charge generateCharge(Pay pay) {
		if(pay.getChannel() == null || pay.getChannel().trim().isEmpty()){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "支付渠道不能为空");
		}
		OrderInfo  orderInfo = orderService.getOrderInfoById(pay.getOrderId());
		if(null == orderInfo){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "未找到ID对应的订单");
		}
		Charge charge = null;
		Map<String, Object> chargeParams = new HashMap<String, Object>();
		chargeParams.put("order_no",  orderInfo.getOrderNo());
		chargeParams.put("amount", orderInfo.getTotalPayee());
		Map<String, String> app = new HashMap<String, String>();
		app.put("id", AjkUtil.PINGXX_APP_ID);
		chargeParams.put("app", app);
		chargeParams.put("channel",  pay.getChannel());
		chargeParams.put("currency", "cny");
		chargeParams.put("client_ip",  pay.getClientIp());
		String subject = "订单号"+orderInfo.getOrderNo();
		try {
			subject = AjkUtil.substring(orderInfo.getOrderTitle(), pay.getChannel(), 32);
		} catch (UnsupportedEncodingException e1) {
			
		}
		chargeParams.put("subject",  subject);
		chargeParams.put("body",  orderInfo.getOrderTitle());
		try {
			charge = Charge.create(chargeParams);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			throw new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (InvalidRequestException e) {
			e.printStackTrace();
			throw new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (APIConnectionException e) {
			e.printStackTrace();
			throw new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (APIException e) {
			e.printStackTrace();
			throw new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		}
		return charge;
	}

}
